package org.mall.modules.product.service.impl;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.mall.common.constant.DeletedStatusEnum;
import org.mall.common.constant.ProductErrorCodeEnum;
import org.mall.common.constant.UserErrorCodeEnum;
import org.mall.common.util.ServiceExceptionUtil;
import org.mall.convert.UserProductSpuCollectionsConvert;
import org.mall.modules.member.entity.Member;
import org.mall.modules.member.service.IMemberService;
import org.mall.modules.member.service.UserProductSpuCollectionsService;
import org.mall.modules.pojo.member.UserProductSpuCollectionsAddDTO;
import org.mall.modules.pojo.member.UserProductSpuCollectionsBO;
import org.mall.modules.pojo.member.UserProductSpuCollectionsUpdateDTO;
import org.mall.modules.pojo.promotion.message.ProductSpuCollectionMessage;
import org.mall.modules.product.entities.ProductSpuDO;
import org.mall.modules.product.mapper.ProductSpuMapper;
import org.mall.modules.product.service.ProductSpuCollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * ProductSpuCollectionServiceImpl
 * @author xiaofeng
 * @date 2019/07/01 23:14
 * @version 1.0
 */
@Service // 实际上不用添加。添加的原因是，必须 Spring 报错提示
public class ProductSpuCollectionServiceImpl implements ProductSpuCollectionService {

    @Autowired
    private ProductSpuMapper productSpuMapper;
    @Autowired
    private UserProductSpuCollectionsService collectionsService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private UserProductSpuCollectionsService userProductSpuCollectionsService;
    @Override
    public boolean productSpuCollection(Long spuId, Integer hasCollectionType, String userId) {
        ProductSpuDO productSpuDO = this.productSpuMapper.selectById(spuId);
        // 校验 Spu 是否存在
        if (productSpuDO == null) {
            throw ServiceExceptionUtil.exception(ProductErrorCodeEnum.PRODUCT_SPU_NOT_EXISTS.getCode());
        }
        UserProductSpuCollectionsAddDTO addDTO=new UserProductSpuCollectionsAddDTO();


        Member member=memberService.getById(userId);
        if (member == null) {
            throw ServiceExceptionUtil.exception(UserErrorCodeEnum.USER_NOT_EXISTS.getCode());
        }
        List<String> result = Lists.newArrayList(Splitter.on(",").omitEmptyStrings().trimResults().split(productSpuDO.getPicUrls()));

        ProductSpuCollectionMessage productSpuCollectionMessage = new ProductSpuCollectionMessage()
                .setSpuId(productSpuDO.getId())
                .setSpuName(productSpuDO.getName())
                .setSpuImage(result.size() > 0 ? result.get(0) : "")
                .setSellPoint(productSpuDO.getSellPoint())
                .setPrice(productSpuDO.getPrice())
                .setHasCollectionType(hasCollectionType)
                .setUserId(userId);
        // 收藏
        if (hasCollectionType.equals(1)) {
            this.saveUserProductSpuCollections(productSpuCollectionMessage, member.getNickName());
        } else if (productSpuCollectionMessage.getHasCollectionType().equals(2)) {
            // 取消收藏
            this.deleteUserProductSpuCollections(productSpuCollectionMessage.getUserId(),
                    productSpuCollectionMessage.getSpuId());
        }
        return Boolean.TRUE;
    }




    /**
     * 保存商品收藏
     * @param productSpuCollectionMessage
     * @param nickname
     * @return
     */
    private int saveUserProductSpuCollections(final ProductSpuCollectionMessage productSpuCollectionMessage,
                                              final String nickname) {
        int result = 0;
        UserProductSpuCollectionsBO userProductSpuCollectionsBO = this.userProductSpuCollectionsService
                .getUserSpuCollectionsByUserIdAndSpuId(productSpuCollectionMessage.getUserId(),
                        productSpuCollectionMessage.getSpuId());
        if (userProductSpuCollectionsBO == null) {
            UserProductSpuCollectionsAddDTO userProductSpuCollectionsAddDTO = UserProductSpuCollectionsConvert.INSTANCE
                    .convert(productSpuCollectionMessage);
            userProductSpuCollectionsAddDTO.setNickname(StringUtils.isEmpty(nickname) ? "" : nickname);
            userProductSpuCollectionsAddDTO.setCreateTime(new Date());
            userProductSpuCollectionsAddDTO.setDeleted(DeletedStatusEnum.DELETED_NO.getValue());
            result = userProductSpuCollectionsService.addUserSkuCollections(userProductSpuCollectionsAddDTO);
        } else {
            // 存在重新收藏
            if (userProductSpuCollectionsBO.getDeleted().equals(DeletedStatusEnum.DELETED_YES.getValue())) {
                UserProductSpuCollectionsUpdateDTO userProductSpuCollectionsUpdateDTO = this
                        .setUserProductSpuCollectionsUpdateDTO(userProductSpuCollectionsBO.getId(),
                                DeletedStatusEnum.DELETED_NO);
                result = this.userProductSpuCollectionsService
                        .updateUserProductSpuCollections(userProductSpuCollectionsUpdateDTO);
            }
        }
        return result;
    }

    /**
     * 取消收藏
     * @param userId
     * @param spuId
     * @return
     */
    private int deleteUserProductSpuCollections(final String userId, final Long spuId) {
        UserProductSpuCollectionsBO userProductSpuCollectionsBO = this.userProductSpuCollectionsService
                .getUserSpuCollectionsByUserIdAndSpuId(userId, spuId);
        int result = 0;
        if (userProductSpuCollectionsBO != null) {
            // 未取消收藏的数据
            if (userProductSpuCollectionsBO.getDeleted().equals(DeletedStatusEnum.DELETED_NO.getValue())) {
                UserProductSpuCollectionsUpdateDTO userProductSpuCollectionsUpdateDTO = this
                        .setUserProductSpuCollectionsUpdateDTO(userProductSpuCollectionsBO.getId(),
                                DeletedStatusEnum.DELETED_YES);
                result = this.userProductSpuCollectionsService
                        .updateUserProductSpuCollections(userProductSpuCollectionsUpdateDTO);
            }
        }
        return result;
    }

    /**
     * 设置更新值
     * @param id
     * @param deletedStatusEnum
     * @return
     */
    private UserProductSpuCollectionsUpdateDTO setUserProductSpuCollectionsUpdateDTO(final Integer id,
                                                                                     final DeletedStatusEnum deletedStatusEnum) {
        return new UserProductSpuCollectionsUpdateDTO().setId(id).setUpdateTime(new Date())
                .setDeleted(deletedStatusEnum.getValue());
    }
}
